package com.fjnu.dao.impl;

import com.fjnu.annotation.NPECatch;
import com.fjnu.dao.UserDao;
import com.fjnu.entity.User;
import javax.sql.DataSource;
import java.sql.*;

@NPECatch
public class UserDaoImpl implements UserDao {
    private DataSource dataSource;

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    @Override
    public void insert(User user) {
        String sql = "INSERT INTO user (user_id, username, password, salt, nickname, email, phone, sex, age, img, status, create_time, update_time, last_login_time) " +
                "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

        try (Connection conn = dataSource.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            // 1. 非空字段赋值（必须设置，否则数据库会报非空错误）
            stmt.setString(1, user.getUserId());
            stmt.setString(2, user.getUsername());
            stmt.setString(3, user.getPassword());
            stmt.setString(4, user.getSalt());
            stmt.setString(5, user.getNickname() != null ? user.getNickname() : ""); // 昵称允许为空，默认空字符串
            stmt.setString(6, user.getEmail() != null ? user.getEmail() : "");       // 邮箱允许为空，默认空字符串
            stmt.setString(7, user.getPhone() != null ? user.getPhone() : "");       // 手机号允许为空，默认空字符串

            // 2. 关键修复：Integer类型字段非空判断（避免NPE）
            stmt.setInt(8, user.getSex() != null ? user.getSex() : 0);                // sex为null时默认0（未知）
            stmt.setInt(9, user.getAge() != null ? user.getAge() : 0);                // age为null时默认0

            stmt.setString(10, user.getImg() != null ? user.getImg() : "");           // 头像允许为空，默认空字符串
            stmt.setInt(11, user.getStatus() != null ? user.getStatus() : 1);         // status为null时默认1（正常）

            // 3. 时间字段赋值（确保不为null，可在User实体类中默认初始化）
            stmt.setTimestamp(12, new Timestamp(user.getCreateTime().getTime()));
            stmt.setTimestamp(13, new Timestamp(user.getUpdateTime().getTime()));
            stmt.setTimestamp(14, user.getLastLoginTime() != null ? new Timestamp(user.getLastLoginTime().getTime()) : null);

            stmt.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException("插入用户失败", e);
        }
    }

    // 其他方法（select、count、mapRowToUser）保持不变...
    @Override
    public User select(String userId) {
        String sql = "SELECT * FROM user WHERE user_id = ?";
        try (Connection conn = dataSource.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setString(1, userId);
            try (ResultSet rs = stmt.executeQuery()) {
                if (rs.next()) {
                    return mapRowToUser(rs);
                }
            }
        } catch (SQLException e) {
            throw new RuntimeException("查询用户失败", e);
        }
        return null;
    }

    @Override
    public int count() {
        String sql = "SELECT COUNT(*) FROM user";
        try (Connection conn = dataSource.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql);
             ResultSet rs = stmt.executeQuery()) {
            if (rs.next()) {
                return rs.getInt(1);
            }
        } catch (SQLException e) {
            throw new RuntimeException("统计用户数量失败", e);
        }
        return 0;
    }


    private User mapRowToUser(ResultSet rs) throws SQLException {
        User user = new User();
        user.setUserId(rs.getString("user_id"));
        user.setUsername(rs.getString("username"));
        user.setPassword(rs.getString("password"));
        user.setSalt(rs.getString("salt"));
        user.setNickname(rs.getString("nickname"));
        user.setEmail(rs.getString("email"));
        user.setPhone(rs.getString("phone"));
        user.setSex(rs.getInt("sex")); // 数据库字段非null，直接赋值
        user.setAge(rs.getInt("age")); // 数据库字段非null，直接赋值
        user.setImg(rs.getString("img"));
        user.setStatus(rs.getInt("status"));
        user.setCreateTime(rs.getTimestamp("create_time"));
        user.setUpdateTime(rs.getTimestamp("update_time"));
        user.setLastLoginTime(rs.getTimestamp("last_login_time"));
        return user;
    }
}